import os
import json

def walk_directory(directory):
    """
    遍历目录并返回目录树的信息。
    """
    data=[]
    cnt=0
    for root, dirs, files in os.walk(directory):
        for file in files:
            cnt+=1
            abs_dir=os.path.join(root, file)
            try:
                data.append({
                    "title":file,
                    "content":open(abs_dir,'r',encoding='utf-8').read(),
                    "dir":abs_dir
                }) 
            except Exception as e:
                print(e)
                print(abs_dir)
    print(f'文件总数为{cnt}')
    return data



def save_to_json(data, json_path):
    """
    将字典保存为 JSON 文件。
    """
    with open(json_path, 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, ensure_ascii=False, indent=2)

if __name__ == '__main__':
    # 要遍历的文件夹路径
    root_dir = '/data/lxy/yangguang'
    # 输出的 JSON 文件路径
    output_json = '/data/lxy/raptor/output.json'

    # 生成目录树的字典形式
    dir_structure = walk_directory(root_dir)
    # 保存到 JSON 文件
    save_to_json(dir_structure, output_json)

    print(f'Directory structure saved to {output_json}')
